<script setup name="FlowDesign">
import { onMounted, ref } from 'vue'
import CodeMirrorEditor from '@/components/CodeMirrorEditor/index.vue'
import { ElMessageBox } from 'element-plus'

import ScWorkflow from '@/components/scWorkflow'
import useFlowStore from '@/store/modules/flow'
import { storeToRefs } from 'pinia'
import { ElMessage } from 'element-plus'
import { copyText } from '@/utils'
const flowStore = useFlowStore()
const { modelContent } = storeToRefs(flowStore)

const formRef = ref()
const drawer = ref(false)
const jsonFormat = ref({})

let form = ref({
	processConfig: {
		nodeName: '发起人',
		type: 0,
		nodeAssigneeList: []
	}
})

// 接口保存审批流程
const saveDesign = json => {
	modelContent.value = JSON.stringify(form.value.processConfig)
}

const updateCompInfo = () => {
	if (modelContent.value) {
		const _val = JSON.parse(modelContent.value)
		form.value = Object.assign({ processConfig: _val }, {})
	}
}

// const copyParseJson = async () => {
// 	await toClipboard(JSON.stringify(jsonFormat.value, null, '  '))
// }

const copyJson = async () => {
	if (!jsonFormat.value) {
		return ElMessage.warning('当前没有数据噢')
	}
	const json = JSON.parse(jsonFormat.value || {})
	copyText(JSON.stringify(json))
}

const validate = () => {
	// 保存表单设计
	saveDesign()
	// 根据后续的业务需求 调整 validate 的功能
	return new Promise((resolve, reject) => {
		resolve()
	})
}
const sureImportJson = () => {
	ElMessageBox.confirm('确定应用JSON模型吗？', '提示', {
		callback: async action => {
			if (action === 'confirm') {
				form.value.processConfig = JSON.parse(jsonFormat.value || {})
				drawer.value = !drawer.value
			} else {
			}
		}
	}).catch(() => {})
}

const openDrawerEv = () => {
	jsonFormat.value = JSON.stringify(form.value.processConfig, null, '  ')
	drawer.value = !drawer.value
}

onMounted(() => {
	updateCompInfo()
})

defineExpose({
	formRef,
	saveDesign,
	validate,
	updateCompInfo
})
</script>

<template>
	<div>
		<div style="z-index: 999" class="fixed top-44 right-48">
			<el-button type="primary" @click="openDrawerEv"> 查看/导入 JSON </el-button>
		</div>

		<ScWorkflow v-model="form.processConfig"></ScWorkflow>

		<el-dialog v-if="drawer" v-model="drawer" class="le-dialog" size="600px" :append-to-body="true" title="查看JSON" destroy-on-close>
			<code-mirror-editor v-model="jsonFormat"></code-mirror-editor>
			<template #footer>
				<el-button type="primary" @click="copyJson">复制 JSON</el-button>
				<el-button @click="sureImportJson">导入JSON</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<style lang="scss"></style>
